from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.conf import settings
from core.user import * 

import md5
import urllib
import time
from datetime import datetime

class FacebookConnectMiddleware(object):
  facebook_user_is_authenticated = False
  def process_request(self, request):
    try:
      if request.user.is_authenticated():
        request.session['login_debug'] = 'zoyoe account';
        return
      if not CONFIG.FB_COOKIE_USR in request.COOKIES:
        request.session['login_debug'] = 'can not detect fb cookie with key:' + CONFIG.FB_COOKIE_USR;
        return;
      user_info_params = {
        'access_token': request.COOKIES[CONFIG.FB_COOKIE_TOKEN],
      }
      user_info_params = urllib.urlencode(user_info_params)
      url = CONFIG.FB_GRAPH_SERVER + request.COOKIES[CONFIG.FB_COOKIE_USR]+"?access_token="+request.COOKIES[CONFIG.FB_COOKIE_TOKEN]
      json_rslt = urllib.urlopen(url).read()
      user_info_response  = json.loads(json_rslt)

      if user_info_response.has_key('error'):
        return

      zoyoe_usr_name = "fb_" + request.COOKIES[CONFIG.FB_COOKIE_USR]
      zoyoe_password = request.COOKIES[CONFIG.FB_COOKIE_USR] + CONFIG.FB_API_SECRET
      zoyoe_password = md5.new(zoyoe_password).hexdigest()


      zoyoe_email = user_info_response['email']

      try:
      # Authenticate then login (or display disabled error message)
        django_user = User.objects.get(username=zoyoe_usr_name)
        user = authenticate(username = zoyoe_usr_name,password= zoyoe_password)
        request.session['login_debug'] = 'authenticate'
        if (user is not None) and user.is_active:
          login(request, user)
          self.facebook_user_is_authenticated = True
        else:
          request.session['login_debug'] = 'authenticate fail'
      except User.DoesNotExist:
      # There is no Django account for this Facebook user.
      # Create one, then log the user in.
        # Create user
        user = User.objects.create_user(zoyoe_usr_name, zoyoe_email, zoyoe_password)
        user.save()
        user = authenticate(username='fb_' + zoyoe_usr_name,
                        password=zoyoe_password)
        if (user is not None) and user.is_active:
          login(request, user)
          self.facebook_user_is_authenticated = True
        else:
          pass
        request.session['login_debug'] = 'create new user'
    #except BaseException,e:
    except User.DoesNotExist,e:
      request.session['login_debug'] = 'unknow exception' + str(e)
      return 

  def process_response(self, request, response):        
    response.delete_cookie(CONFIG.FB_COOKIE_USR)
    response.delete_cookie(CONFIG.FB_COOKIE_TOKEN)
    return response
